<?php

class DriversController extends CController
{
	const PAGE_SIZE=10;

	/**
	 * @var string specifies the default action to be 'list'.
	 */
	public $defaultAction='create';

	/**
	 * @var CActiveRecord the currently loaded data model instance.
	 */
	private $_model;

	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
			array('application.filters.LoginFilter'),
			array('application.filters.AuthFilter'),
			array('application.filters.DeleteFilter + delete'),
		);
	}

	/**
	 * Shows a particular model.
	 */
	public function actionShow()
	{	
		$this->render('show',array('model'=>$this->loadDrivers()));
	}

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'show' page.
	 */
	public function actionCreate()
	{
		$model=new Drivers;
		if(isset($_POST['Drivers']))
		{
			$model->attributes=$_POST['Drivers'];
			if($model->save()){
				//$this->render('show',array('model'=>$model,'ret'=>'create','info'=>'添加成功！'));
				//return;
				$this->redirect(array('show','id'=>$model->id,'ret'=>'create','ok'=>'0'));
			}	
		}
		$this->render('create',array('model'=>$model));
	}

	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'show' page.
	 */
	public function actionUpdate()
	{
		$model=$this->loadDrivers();
		if(isset($_POST['Drivers']))
		{
			$model->attributes=$_POST['Drivers'];
			if($model->save()){
				//$this->render('show',array('model'=>$model,'ret'=>'admin','info'=>'更新成功！'));
				//return;  //render方法执行后还会继续执行后面语句，故增加retuen
				$this->redirect(array('show','id'=>$model->id,'ret'=>'admin','ok'=>'1')+$_GET);
			}
		}
		$this->render('update',array('model'=>$model));
	}

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'list' page.
	 */
	public function actionDelete()
	{
		if(isset($_GET['id'])){
			Drivers::model()->updateByPk($_GET['id'],array('state'=>1));
			//$this->actionAdmin();
			unset($_GET['id']);
			$this->redirect(array('admin')+$_GET);
		}
		else
			throw new CHttpException(400,'无法获得要删除的信息ID!');
	}

	/**
	 * Manages all models.
	 */
	public function actionAdmin()
	{	
		$this->search(false);
	}
	
	public function actionSearch(){
		$this->search();
	}
	
	private function search($method=true){
		$criteria=new CDbCriteria();
		$criteria->join='LEFT JOIN trucks ON trucks.fk_driver_id=drivers.id';
		$criteria->select='drivers.*,trucks.plate_no as plate_no';
		$criteria->addCondition('drivers.state=0');
		$blur=true;
		if(Yii::app()->getRequest()->isPostRequest){
			if(isset($_POST['keys'])){//页面传来的搜索关键字数组
				$_GET['keys']=$_POST['keys'];
			}
		}
		if(isset($_GET['keys'])){
			if(isset($_GET['keys']['blur'])&&$_GET['keys']['blur']=='0') $blur=false;
			foreach($_GET['keys'] as $key=>$val){
				if(trim($val)=='')
					unset($_GET['keys'][$key]);
				else if($key!='blur'){//按照模糊或精确查询
					$blur?$criteria->addSearchCondition($key,$val):$criteria->addCondition("{$key}='{$val}'");
				}
			}
		}
		$model=Drivers::model();
		$pages=new CPagination($model->count($criteria));
		$pages->pageSize=Yii::app()->params['page_size']['drivers'];
		$pages->applyLimit($criteria);
		
		$sort=new CSort('Drivers');
		$sort->attributes=array_merge($model->attributeNames(),array('plate_no'));
		$sort->applyOrder($criteria);
    	$models=$model->findAll($criteria);
		$this->render('admin',array(
			'models'=>$models,
			'pages'=>$pages,
			'sort'=>$sort,
			'search'=>$method,
		));
	}

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer the primary key value. Defaults to null, meaning using the 'id' GET variable
	 */
	public function loadDrivers($id=null)
	{
		if($this->_model===null)
		{
			if($id!==null || isset($_GET['id']))
				$this->_model=Drivers::model()->findbyPk($id!==null ? $id : $_GET['id']);
			if($this->_model===null)
				throw new CHttpException(404,'The requested page does not exist.');
		}
		return $this->_model;
	}
	
	public function loadDriversWithTruck($id=null)
	{
		if($id!==null || isset($_GET['id'])){
				$criteria=new CDbCriteria();
				$criteria->join='LEFT JOIN trucks ON trucks.fk_driver_id=drivers.id';
				$criteria->select='drivers.*,trucks.plate_no as plate_no';
				$criteria->addCondition('drivers.id='.($id!==null ? $id : $_GET['id']));
				$this->_model=Drivers::model()->find($criteria);
			}
		return $this->_model;
	}
}
